import os

from django.conf import settings
from django.shortcuts import render

from contents.models import ContentCategory
from contents.utils import get_categories


def generate_static_index_html():
    categories = get_categories()  # 方法调用
    contents = {}  # 用来装所有广告数据的字典
    contentCategory_qs = ContentCategory.objects.all()  # 获取广告所有分类
    for category in contentCategory_qs:  # 遍历获取每一条广告
        # 将获取的每一条广告添加字典中去
        contents[category.key] = category.content_set.filter(status=True).order_by('sequence')

    context = {
        "categories": categories,
        'contents': contents

    }

    response = render(None, "index.html", context)
    html_text = response.content.decode()
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)